"use server";
import { getFileById } from "@/data/file";
import { isUrl } from "@/lib/utils";
import { FileType } from "@/lib/enums";
import path from "path";
import fs from "fs/promises";
import { randomUUID } from "crypto";
import prisma from "@/lib/prisma";

export const GetImageAction = async (image: string) => {
  if (image) {
    if (!isUrl(image)) {
      const file = await getFileById(image);
      if (file) {
        if (file.type === FileType.Local) {
          return `${process.env.NEXT_PUBLIC_APP_URL}/image/${file.id}`;
        } else {
          return file.data ?? "";
        }
      }
    } else {
      return image;
    }
  } else {
    return null;
  }
};

export const UploadAction = async (files: FileList) => {
  if (files && files.length > 0) {
    console.log(files);
    const file = files[0] as File;
    const originalName = file.name;
    const fileType = process.env.STORAGE_TYPE
      ? parseInt(process.env.STORAGE_TYPE)
      : FileType.Local;
    if (fileType === FileType.Local) {
      try {
        const uploadDir = path.join(process.cwd(), process.env.STORAGE_UPLOAD_PATH as string);
        await fs.mkdir(uploadDir, { recursive: true });

        const fileExtension = file.name.split(".").pop();
        const fileName = `${randomUUID()}.${fileExtension}`;
        const filePath = path.join(uploadDir, fileName);

        const bytes = await file.arrayBuffer();
        const buffer = Buffer.from(bytes);
        await fs.writeFile(filePath, buffer);
        const data = `${fileName}`;
        const f = await prisma.file.create({
          data: {
            originalName,
            data,
            type: FileType.Local,
          },
        });

        return f.id;
      } catch (error) {
        console.log(error);
        return null;
      }
    }
  }
  return null;
};
